package com.ld.caodan.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpStatus;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.FloatMath;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.ld.caodan.common.ContentLoader;
import com.ld.caodan.entity.Article;
import com.ld.caodan.util.NumberUtils;


/**
 * 详细页面
 * 
 * @author LD
 *
 * 上午11:46:05  2012-9-14
 */
public class CD_Article_Info_Activity extends BasicActivity implements OnTouchListener{
	
	private ZoomControls controls;
	TextView contentView;
	TextView titleView;
	private float textSize = 20;
	private static final float MAX_TEXT_SIZE = 30;
	private static final float MIN_TEXT_SIZE = 20;
	private long showZoomControlsTime ;
	private ScrollView scroll;
	
	private Button ding;
	private Button cai;
	
	@Override
	protected void initContentView() {
		setContentView(R.layout.info_view);
	}

	@Override
	protected void initTopTitle() {
	
	}

	Article info;
	
	boolean hasLuanma(){
		return true;
	}
	
	@Override
	protected void initView() {
		Intent intent = getIntent();
		info = (Article) intent.getSerializableExtra("info");
		//单独取顶和踩
		setDingCaiCount(info.getId());
		if(hasLuanma()){//没有乱码  
			
		}else{//有乱码 重新取内容
			
		}
		scroll = (ScrollView)findViewById(R.id.sv);
		scroll.setOnTouchListener(this);
		contentView = (TextView)findViewById(R.id.info_text);
		contentView.setText(Html.fromHtml(info.getContent()));
		contentView.setTextSize(textSize);
		titleView = (TextView) findViewById(R.id.info_title);
		titleView.setText(info.getColumn());
		controls = (ZoomControls)findViewById(R.id.zoomControls1);
		controls.hide();
		controls.setZoomSpeed(300);
		ding = (Button)findViewById(R.id.ding);
		ding.setText("顶一下("+info.getDing()+")");
		ding.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//发送异步请求  并刷新页面数据
				new Thread(new DingCaiSubmiter(Type.good,info.getId())).start();
			}
		});
		cai = (Button) findViewById(R.id.cai);
		cai.setText("踩一下("+info.getCai()+")");
		cai.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//发送异步请求  并刷新页面数据
				new Thread(new DingCaiSubmiter(Type.bad,info.getId())).start();
			}
		});
		controls.setOnZoomInClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showZoomControlsTime = System.currentTimeMillis();
				textSize+=2;
				onMaxSizeDoSomething();
				contentView.setTextSize(textSize);
			}

			
		});
		controls.setOnZoomOutClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showZoomControlsTime = System.currentTimeMillis();
				textSize-=2;
				onMinSizeDoSomething();
				contentView.setTextSize(textSize);
			}

		});
	}
	
	void setDingCaiCount(String id){
		final String ding_cai_count_Url = "http://www.caodan.cc/plus/digg_ajax.php?id="+id;
			new Thread(new Runnable() {
				public void run() {
					try {
						Document dingcaiDoc = Jsoup.parse(new URL(ding_cai_count_Url),
								ContentLoader.timeOut);
						Elements docElements = dingcaiDoc
								.getElementsByAttributeValue("class", "digg_num");
						if (docElements != null && docElements.size() > 0) {
							Message message = handler.obtainMessage();
							message.what = HttpStatus.SC_OK;
							message.arg1 = Integer.parseInt(NumberUtils
									.getNum(docElements.get(0).text()));
							System.out.println("顶---》"+message.arg1);
							message.arg2 = Integer.parseInt(NumberUtils
									.getNum(docElements.get(1).text()));
							System.out.println("踩---》"+message.arg2);
							handler.sendMessage(message);
						}
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
	}
	
	private float onMinSizeDoSomething() {
		if(textSize<=MIN_TEXT_SIZE){
			controls.setIsZoomInEnabled(true);
			controls.setIsZoomOutEnabled(false);
			textSize = MIN_TEXT_SIZE;
		}else{
			controls.setIsZoomInEnabled(true);
			controls.setIsZoomOutEnabled(true);
		}
		return textSize;
	}
	
	private float onMaxSizeDoSomething() {
		if(textSize>=MAX_TEXT_SIZE){
			controls.setIsZoomInEnabled(false);
			controls.setIsZoomOutEnabled(true);
			textSize = MAX_TEXT_SIZE;
		}else{
			controls.setIsZoomInEnabled(true);
			controls.setIsZoomOutEnabled(true);
		}
		return textSize;
	}
	
	
	enum Type{
		good,bad;
	}
	
	public class DingCaiSubmiter implements Runnable{
		
		private String url = "http://caodan.cc/plus/digg_ajax.php?action=%s&id=%s";
		
		private Type type;
		private String id;
		
		public DingCaiSubmiter(Type type,String id) {
			this.type = type;
			this.id = id;
			url = String.format(url, type.name(),id);
		}
		
		@Override
		public void run() {
			Connection connection = Jsoup.connect(url);
			try {
				int status = connection.execute().statusCode();
				Message message = handler.obtainMessage();
				message.what = status;
				message.obj = type;
				if(status==HttpStatus.SC_OK){
					if(type == Type.good){
						int dingcount = info.getDing();
						message.arg1 = ++dingcount;
					}else if(type == Type.bad){
						int caicount = info.getCai();
						message.arg2 = ++caicount;
					}
				}
				handler.sendMessage(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void initListener() {
		
	}

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0){//隐藏控件
				if(controls.isShown()){
					controls.hide();
					return;
				}
			}
			else if(msg.what == HttpStatus.SC_OK){//更新 "踩/顶" 数量
				if(msg.obj == Type.good){
					System.out.println("顶一下----------------"+msg.arg1);
					ding.setText("顶一下("+(msg.arg1)+")");
					info.setDing(msg.arg1);
				}else if(msg.obj == Type.bad){
					System.out.println("踩一下----------------"+msg.arg2);
					cai.setText("踩一下("+(msg.arg2)+")");
					info.setCai(msg.arg2);
				}else{
					info.setDing(msg.arg1);
					info.setCai(msg.arg2);
					ding.setText("顶一下("+(msg.arg1)+")");
					cai.setText("踩一下("+(msg.arg2)+")");
				}
			}
		};
	};
	
	float beforeSpace = 0;
	float afterSpace = 0;
	
	 /** 
     * 就算两点间的距离 
     */  
    private float spacing(MotionEvent event) {  
        float x = event.getX(0) - event.getX(1);  
        float y = event.getY(0) - event.getY(1);  
        return FloatMath.sqrt(x * x + y * y);  
    } 
    
    private boolean ZOOM = false;
    
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int action = event.getAction() & MotionEvent.ACTION_MASK;
		switch(action){
		case MotionEvent.ACTION_POINTER_DOWN:
			ZOOM = true;
			beforeSpace = spacing(event);
			break;
		case MotionEvent.ACTION_DOWN:
			if(event.getPointerCount()==2)  
				 beforeSpace = spacing(event);  
			showZoomControlsTime = System.currentTimeMillis();
			// 如果没显示就显示 如果显示就消失
			if (!controls.isShown()) {
				controls.show();
				// 每次点击后DISMISS_DELAY秒后消失
				handler.post(runnable);
			} else {
				// 正在倒计时 可以直接让其消失
				if (isShowTop) {
					handler.sendEmptyMessage(0);
				}
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (controls.isShown()) {
				controls.hide();
			}
			if (event.getPointerCount() >= 2) {
				System.out.println("-----------2----------"+event.getPointerCount());
				if (ZOOM) {
					if (spacing(event) > 10f) {
						afterSpace = spacing(event);
						float gapLenght = afterSpace - beforeSpace;
						if (gapLenght == 0) {
							return false;
						} else if (Math.abs(gapLenght) > 5f) {
							if (gapLenght > 0) { // 放大
								textSize +=2;
								textSize = onMaxSizeDoSomething();
								System.out.println("大大大大大大大大大大大"+textSize);
								contentView.setTextSize(textSize);
							} else if ((gapLenght <= 0)) { // 缩小
								textSize -=2;
								textSize = onMinSizeDoSomething();
								contentView.setTextSize(textSize);
								System.out.println("小小小小小小小小小小小"+textSize);
							}
							beforeSpace = afterSpace;
						}
					}
				}
			}
			break;
		}
		return super.onTouchEvent(event);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	boolean isShowTop = false;
	
	/**
	 * 每次Zoom按钮显示时间
	 */
	private static final long DISMISS_DELAY = 8*1000;
	
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if(System.currentTimeMillis()-showZoomControlsTime<=DISMISS_DELAY){
				isShowTop = true;
				handler.post(runnable);
			}else{
				handler.sendEmptyMessage(0);
			}
		}
	};

}
